package com.dh.test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SocketTimePrint {

	protected final static Logger log = LoggerFactory.getLogger(SocketTimePrint.class);

	public static void main(String args[]) {
		Thread server = new Thread(new ServerMsgNoselector());
		Thread client = new Thread(new ClientMsg());
        try {
        	
        	//log.info("Beginning to start the server for message");
    		server.start();
    		//Thread.sleep(100);
    		//log.info("Beginning to start the client for message");
    		client.start();
    		
		} catch (Exception e) {
			e.printStackTrace();
		}
		

	}
}

class ClientMsg implements Runnable {

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			SocketChannel socket = SocketChannel.open();
			socket.connect(new InetSocketAddress("127.0.0.1", 9999));
			socket.configureBlocking(true);
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			while (true) {
				String datestr = format.format(new Date());
				ByteBuffer buff = ByteBuffer.wrap(datestr.getBytes());
				socket.write(buff);
				Thread.sleep(2000);
			}
		} catch (IOException | InterruptedException ie) {
			ie.printStackTrace();
		}
	}

}

class ServerMsgNoselector implements Runnable {
	//protected final Logger log = LoggerFactory.getLogger(this.getClass());

	@Override
	public void run() {
		try {
			// 打开ServerSocketChannel
			ServerSocketChannel serverChannel = ServerSocketChannel.open();
			//绑定端口
			ServerSocket socket = serverChannel.socket();
			socket.bind(new InetSocketAddress(9999));
			//设置成阻塞的
			serverChannel.configureBlocking(true);
            //监听新进来的连接
			SocketChannel client = serverChannel.accept();
			client.configureBlocking(true);
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			while (true) {
				if(null!=client) {
					int len = client.read(buffer);
					if (len > 0 && buffer.hasArray()) {
						String msg = new String(buffer.array(), 0, len);
						System.out.println(msg);
						//log.info("The recvicing message is " + msg);
					} else {
						System.out.println("Waiting for message ...");
						//log.info("Waiting for message ...");
					}
					buffer.clear();
				}
				
			}
		} catch (Exception ie) {
			ie.printStackTrace();
		}

	}

}